<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--管理员数据-->
      <el-col :span="24" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          class="queryForm"
          :inline="true"
          v-show="showSearch"
          size="mini"
          label-width="68px"
        >
          <el-form-item prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="管理员账号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <!-- <el-form-item prop="isEnable">
            <el-select
              v-model="queryParams.isEnable"
              placeholder="状态"
              clearable
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item> -->

          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:manager:add']"
              >新增</el-button
            >
          </el-form-item>
        </el-form>

        <el-table
          v-loading="loading"
          class="dense-table"
          :data="userList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            label="管理员编号"
            key="userId"
            prop="userId"
            width="280px"
          />
          <el-table-column
            label="管理员账号"
            key="userName"
            prop="userName"
            :show-overflow-tooltip="true"
          />
          <!-- <el-table-column
            label="显示名"
            key="displayName"
            prop="displayName"
            :show-overflow-tooltip="true"
          /> -->
          <!-- <el-table-column
            label="部门"
            key="department"
            prop="department"
            :show-overflow-tooltip="true"
          /> -->
          <el-table-column label="角色" key="roles" align="left">
            <template slot-scope="scope">
              <el-tag
                style="margin-right: 5px"
                size="mini"
                v-for="role in scope.row.roleIds"
                :key="role"
              >
                {{ roleOptions.find((n) => n.roleID == role).roleName }}
              </el-tag>
            </template> </el-table-column
          >/>
          <!-- <el-table-column label="状态" align="center" key="isEnable">
            <template slot-scope="scope">
              <el-switch
                :value="scope.row.isEnable"
                :active-value="true"
                :inactive-value="false"
              ></el-switch>
            </template>
          </el-table-column> -->

          <el-table-column
            label="操作"
            align="left"
            width="190"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="showEditDialog(scope.row)"
                >分配角色</el-button
              >
              <el-button
                size="mini"
                type="text"
                @click="showDataPermissionDialog(scope.row)"
                >数据权限</el-button
              >
              <!-- <el-button
                size="mini"
                type="text"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:manager:edit']"
                >修改</el-button
              > -->
              <el-button
                v-if="scope.row.userName !== 'admin'"
                size="mini"
                type="text"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:manager:delete']"
                >删除</el-button
              >
              <!-- -->
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <!-- <el-dialog :title="title" :visible.sync="open" width="600px" :append-to-body="true"
      :modal-append-to-body="true">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="显示名" prop="displayName">
              <el-input v-model="form.displayName" placeholder="请输入显示名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="department">
              <el-input
                v-model="form.department"
                placeholder="请输入归属部门"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="mobile">
              <el-input
                v-model="form.mobile"
                placeholder="请输入手机号码"
                maxlength="11"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="mail">
              <el-input
                v-model="form.mail"
                placeholder="请输入邮箱"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              v-if="form.userId == undefined"
              label="管理员账号"
              prop="userName"
            >
              <el-input
                v-model="form.userName"
                placeholder="请输入管理员名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="form.userId == undefined"
              label="管理员密码"
              prop="password"
            >
              <el-input
                v-model="form.password"
                placeholder="请输入管理员密码"
                type="password"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="角色">
              <el-select
                v-model="form.roleIds"
                multiple
                placeholder="请选择"
                style="width:100%"
              >
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleID"
                  :label="item.roleName"
                  :value="item.roleID"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="是否启用">
              <el-switch
                v-model="form.isEnable"
                :active-value="true"
                :inactive-value="false"
              ></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog> -->

    <!-- 添加平台管理员 -->
    <el-dialog title="添加平台管理员" width="550px" :visible.sync="open">
      <!-- @submit.native.prevent
      @keyup.enter="searchPerson" -->
      <el-form
        style="width: 400px; margin: 0 auto"
        :model="form"
        ref="form"
        label-width="80px"
        :rules="{
          userName: [
            {
              required: true,
              message: '请输入账号或用户名进行搜索',
              trigger: 'blur',
            },
          ],
        }"
      >
        <el-form-item label="账号" prop="userName">
          <el-input
            v-model="form.userName"
            autocomplete="off"
            placeholder="请输入账号"
            :validate-event="false"
            @input="inputChange"
          >
            <template slot="append"
              ><el-button
                icon="el-icon-search"
                type="primary"
                style=""
                @click="searchPerson"
                >检测</el-button
              ></template
            >
          </el-input>
        </el-form-item>
        <el-form-item label="组织" v-if="form.fullDepartment">
          <span>{{ form.fullDepartment }}</span>
        </el-form-item>
        <el-dialog
          width="600px"
          title="选择人员"
          :visible.sync="form.searchPersonResult.show"
          :append-to-body="true"
          :modal-append-to-body="true"
        >
          <template>
            <el-table
              size="mini"
              height="250px"
              highlight-current-row
              empty-text="未找到符合条件的数据"
              @current-change="handleCurrentRowChanged"
              :data="form.searchPersonResult.list"
            >
              <el-table-column
                label="账号"
                width="150px"
                prop="samAccountName"
              />
              <el-table-column label="显示名" prop="displayName" />
              <el-table-column
                label="部门"
                width="300px"
                prop="fullDepartment"
              />
            </el-table>
            <pagination
              style="text-align: right"
              :total="form.searchPersonResult.page.total"
              small
              layout="prev, pager, next"
              :page.sync="form.searchPersonResult.page.pageNum"
              :limit.sync="form.searchPersonResult.page.pageSize"
              @pagination="searchPerson"
            />
            <div slot="footer" class="dialog-footer">
              <el-button @click="form.searchPersonResult.show = false"
                >取 消</el-button
              >
              <el-button type="primary" @click="confirmSelectPerson()"
                >确 定</el-button
              >
            </div>
          </template>
        </el-dialog>
        <el-form-item label="角色">
          <el-select
            v-model="form.roleIds"
            multiple
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.roleID"
              :label="item.roleName"
              :value="item.roleID"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改管理员角色 -->
    <el-dialog title="角色分配" width="550px" :visible.sync="showRoleDialog">
      <!-- @submit.native.prevent
      @keyup.enter="searchPerson" -->
      <el-form
        style="width: 400px; margin: 0 auto"
        :model="form"
        ref="form"
        label-width="80px"
      >
        <el-form-item label="账号">
          {{ form.userName }}
        </el-form-item>
        <el-form-item label="角色">
          <el-select
            v-model="form.roleIds"
            multiple
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.roleID"
              :label="item.roleName"
              :value="item.roleID"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="confirmAssignRoles">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      title="修改密码"
      :visible.sync="changePasswordDialogVisible"
      width="450px"
      :append-to-body="true"
      :modal-append-to-body="true"
      @close="() => (changePasswordForm = {})"
    >
      <el-form
        ref="changePasswordForm"
        :model="changePasswordForm"
        :rules="rulesChangePassword"
        label-width="80px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="changePasswordForm.oldPassword"
            placeholder="输入原密码"
            type="password"
            clearable
          >
            <svg-icon
              slot="prefix"
              icon-class="password"
              class="el-input__icon input-icon"
          /></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="changePasswordForm.newPassword"
            type="password"
            clearable
            placeholder="输入新密码"
          >
            <svg-icon
              slot="prefix"
              icon-class="password"
              class="el-input__icon input-icon"
          /></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            type="password"
            clearable
            v-model="changePasswordForm.confirmPassword"
            placeholder="再次输入密码进行确认"
          >
            <svg-icon
              slot="prefix"
              icon-class="password"
              class="el-input__icon input-icon"
          /></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleChangePassword"
          >确 定</el-button
        >
        <el-button
          @click="
            currentUser = undefined;
            changePasswordDialogVisible = false;
          "
          >取 消</el-button
        >
      </div>
    </el-dialog>

    <!-- 分配数据权限弹窗 -->
    <el-dialog
      title="分配数据权限"
      :visible.sync="dataPermissionDialogVisible"
      width="450px"
      :append-to-body="true"
      :modal-append-to-body="true"
    >
      <el-form>
        <el-form-item label="数据权限">
          <el-checkbox
            v-model="treeProps.expandAll"
            @change="handleCheckedTreeExpand($event)"
            >展开/折叠</el-checkbox
          >
          <el-checkbox
            v-model="treeProps.checkAll"
            @change="handleCheckedTreeNodeAll($event)"
            >全选/全不选</el-checkbox
          >
          <el-checkbox
            v-model="treeProps.checkStrictly"
            @change="handleCheckedTreeConnect($event)"
            >父子联动</el-checkbox
          >
          <el-tree
            lazy
            class="tree-border"
            :data="dataPermissionList"
            :default-checked-keys="checkedKeys"
            :default-expanded-keys="expandedKeys"
            show-checkbox
            ref="dataPermission"
            node-key="id"
            :check-strictly="!treeProps.checkStrictly"
            empty-text="加载中，请稍后"
            :props="defaultProps"
            :load="loadNode"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveDataPermission">确 定</el-button>
        <el-button @click="dataPermissionDialogVisible = false"
          >取 消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changePassword,
  changeUserStatus,
  assignRoles,
} from "@/api/system/user";

import { getAllRoles } from "@/api/system/role";
import dataPermissionApi from "@/api/system/dataPermission";
import personApi from "@/api/activeDirectory/person";
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";

export default {
  name: "manager",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 管理员表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],

      currentUser: undefined,

      // 状态数据字典
      statusOptions: [],
      // 性别状态字典
      sexOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {
        userName: "",
        fullDepartment: "",
        roleIds: [],
        searchPersonResult: {
          show: false,
          loading: false,
          list: [],
          currentRow: undefined,
          page: { pageNum: 1, pageSize: 5, total: 0 },
        },
      },
      changePasswordDialogVisible: false,

      changePasswordForm: {
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
      },
      defaultProps: {
        children: "children",
        label: "label",
        isLeaf: "isLeaf",
      },
      // 管理员导入参数
      upload: {
        // 是否显示弹出层（管理员导入）
        open: false,
        // 弹出层标题（管理员导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的管理员数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        mobile: undefined,
        isEnable: undefined,
        department: undefined,
      },
      // 列信息
      columns: [
        { key: 0, label: `管理员编号`, visible: true },
        { key: 1, label: `管理员账号`, visible: true },
        { key: 2, label: `显示名`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true },
      ],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "管理员名称不能为空", trigger: "blur" },
        ],
        displayName: [
          { required: true, message: "显示名不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "管理员密码不能为空", trigger: "blur" },
        ],
        mail: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        mobile: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      rulesChangePassword: {
        oldPassword: [
          { required: true, message: "原密码不能为空", trigger: "blur" },
        ],
        newPassword: [
          { required: true, message: "新密码不能为空", trigger: "blur" },
        ],
        confirmPassword: [
          {
            validator: (rule, value, callback) => {
              if (value != this.changePasswordForm.newPassword) {
                return callback(new Error("2次输入密码不一致！"));
              }
              return callback();
            },
            trigger: "blur",
          },
        ],
      },

      dataPermissionDialogVisible: false,

      dataPermissionList: [],
      checkedKeys: [],
      expandedKeys: [],
      treeProps: {
        expandAll: false,
        checkAll: false,
        checkStrictly: true,
      },
      currentManagerObjectGuid: "",
      showRoleDialog: false,
    };
  },
  computed: {
    inputUserName() {
      return this.form.userName;
    },
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
    dataPermissionDialogVisible(val) {
      if (!val) this.resetDataPermissionDialog();
    },
    inputUserName(newVal, oldVal) {
      // if (this.form.searchPersonResult.show) return;
      // if (newVal && this.form.fullDepartment) {
      //   this.form.fullDepartment = "";
      // }
    },
  },
  created() {
    this.getList();

    this.statusOptions = [
      { label: "启用", value: true },
      { label: "禁用", value: false },
    ];

    this.sexOptions = [
      { label: "男", value: 1 },
      { label: "女", value: 0 },
    ];

    // this.initPassword = 123456;
    // this.getConfigKey("sys.user.initPassword").then(response => {
    //   this.initPassword = response.msg;
    // });
  },
  methods: {
    inputChange() {
      this.form.fullDepartment = "";
    },
    /** 查询管理员列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams)
        .then((response) => {
          this.userList = response.data.data;
          this.total = response.data.pagination.dataCount;
          this.loading = false;
        })
        .catch()
        .finally((n) => {
          this.loading = false;
        });
      this.getRoleOptions();
    },

    async showEditDialog(row) {
      this.showRoleDialog = true;
      this.form.userId = row.userId;
      this.form.userName = row.userName;
      this.form.roleIds = row.roleIds;
      // this.form = { ...row };
      // this.form.password = this.initPassword;
      var res = await getAllRoles();
      if (res && res.success) {
        this.roleOptions = res.data;
      }
    },

    async confirmAssignRoles() {
      console.log(this.form);

      const res = await assignRoles(this.form.userId, this.form.roleIds);
      if (res && res.success) {
        this.$message.success("分配成功");
        this.showRoleDialog = false;
        this.getList();
      }
    },

    async showDataPermissionDialog(row) {
      this.dataPermissionDialogVisible = true;
      this.currentManagerObjectGuid = row.objectGuid;
      const res = await dataPermissionApi.menuTree({
        objectGuid: this.currentManagerObjectGuid,
      });
      if (res.success) {
        this.dataPermissionList = res.data.all;
        this.checkedKeys = res.data.checkedKeys;
        this.expandedKeys = res.data.expandedKeys;

        this.$nextTick(() => {
          this.rootNode = this.dataPermissionList[0];
          const currentKey = this.dataPermissionList[0].id;
          this.expandKeys = [currentKey];
          if (this.$refs["tree"]) {
            this.$refs["tree"].setCurrentKey(currentKey);
            const currentNode = this.$refs["dataPermission"].getCurrentNode();
            this.handleNodeClick(currentNode);
          }
        });
      }
    },

    async loadNode(node, resolve) {
      if (node.level == 0) {
        //默认加载第1层.
        return resolve(this.dataPermissionList);
      } else if (node.level == 1) {
        //默认展开的层级,需要默认几层就判断一下.
        return resolve(node.data.children); //核心是这里,每次展开的时候loadNode方法就会调用一次,只需要把node.data.[这里是默认的child字段]  加载到resolve方法里就可以了.就可以实现默认加载N级,之后再使用懒加载
      } else {
        const res = await dataPermissionApi.sublist({
          objectGuid: this.currentManagerObjectGuid,
          dn: node.data.id,
        });
        if (res.success) {
          resolve(res.data.all);
        } else {
          resolve([]);
        }
      }
    },

    //检测用户
    async checkPerson() {
      if (!this.form.userName) {
        this.$message.warning("请输入员工账号！");
        return;
      }
      const res = await personApi.info(this.form.userName).catch();
      if (res.success && res.data) {
        this.form.fullDepartment = res.data.fullDepartment;
      } else {
        this.$message.warning("未找到此员工！");
      }
    },
    async saveDataPermission() {
      var checkedNodes = this.$refs.dataPermission.getCheckedNodes();
      console.log(checkedNodes);

      const halfCheckedKNodes = this.$refs.dataPermission.getHalfCheckedNodes();
      console.log(halfCheckedKNodes);

      // checkedNodes = checkedNodes.filter(n => !halfCheckedKeys.includes(n.id));

      // console.log(checkedNodes);

      var all = checkedNodes.map((n) => {
        return {
          objectGuid: this.currentManagerObjectGuid,
          dn: n.id,
          parentDn: n.parentId,
          type: "all",
        };
      });

      var half = halfCheckedKNodes.map((n) => {
        return {
          objectGuid: this.currentManagerObjectGuid,
          dn: n.id,
          parentDn: n.parentId,
          type: "half",
        };
      });
      console.log(1);
      var list = all.concat(half);
      const getRoot = (node) => {
        if (node.type == "all") {
          if (node.parentDn) {
            var parent = list.find((a) => a.dn == node.parentDn);
            if (parent && parent.type == "all") {
              return getRoot(parent);
            } else {
              return node;
            }
          } else {
            return node;
          }
        } else {
          return node;
        }
      };

      var result = [];

      list.forEach((element) => {
        const root = getRoot(element);
        if (!result.find((a) => a.dn == root.dn)) result.push(root);
      });

      const res = await dataPermissionApi.assign(
        this.currentManagerObjectGuid,
        result
      );
      if (res.success) {
        this.$message.success("分配数据权限成功！");
        this.dataPermissionDialogVisible = false;
      }
    },

    resetDataPermissionDialog() {
      this.dataPermissionList = [];
      this.checkedKeys = [];
      this.expandedKeys = [];
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value) {
      let treeList = this.dataPermissionList;
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.dataPermission.store.nodesMap[treeList[i].id].expanded =
          value;
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value) {
      this.$refs.dataPermission.setCheckedNodes(
        value ? this.dataPermissionList : []
      );
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value) {
      this.treeProps.checkStrictly = value ? true : false;
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userName: "",
        fullDepartment: "",
        roleIds: [],
        searchPersonResult: {
          show: false,
          loading: false,
          list: [],
          currentRow: undefined,
          page: { pageNum: 1, pageSize: 5, total: 0 },
        },
      };
      this.resetForm("form");
    },
    async getRoleOptions() {
      var res = await getAllRoles();
      if (res && res.success) {
        this.roleOptions = res.data;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    async handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加管理员";
      // this.form.password = this.initPassword;
      var res = await getAllRoles();
      if (res && res.success) {
        this.roleOptions = res.data;
      }
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();

      const userId = row.userId;
      // this.roleOptions = response.roles;
      getUser(userId).then((response) => {
        this.form = response.data;
        this.form.roleIds = response.data.roleIds;
      });
      this.open = true;
      this.title = "修改管理员";
      this.form.password = "";
      var res = await getAllRoles(userId);
      if (res && res.success) {
        this.roleOptions = res.data;
      }
    },

    /** 重置密码按钮操作 */
    showChangePassword(row) {
      this.currentUser = row;
      this.changePasswordDialogVisible = true;
    },

    handleChangePassword() {
      this.$refs["changePasswordForm"].validate((valid) => {
        if (valid) {
          changePassword(this.currentUser.userId, this.changePasswordForm).then(
            (response) => {
              if (response.success) {
                this.msgSuccess(`修改成功`);
                this.changePasswordDialogVisible = false;
                this.currentUser = undefined;
              }
            }
          );
        }
      });
    },

    handleResetPwd(row) {
      this.$confirm('是否重置管理员编号为"' + row.userId + '"密码?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(123);
          resetUserPwd(row.userId).then((response) => {
            if (response.success) {
              this.msgSuccess(`密码已经重置为${response.data}`);
            }
          });
        })
        .catch(() => {});
    },
    /** 提交按钮 */
    submitForm: function () {
      if (this.form.fullDepartment) {
        addUser(this.form).then((response) => {
          if (response.success) {
            this.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          }
        });
      } else {
        this.$message.warning("请输入员工账号并成功检测！");
      }
      return;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.userId != undefined) {
            updateUser(this.form).then((response) => {
              this.msgSuccess("修改成功");
              if (response.success) {
                this.open = false;
                this.getList();
              }
            });
          } else {
            addUser(this.form).then((response) => {
              if (response.success) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$confirm(
        '是否确认删除管理员编号为"' + userIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delUser(userIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },

    //搜索人员表格行切换
    handleCurrentRowChanged(current, old) {
      this.form.searchPersonResult.currentRow = current;
    },
    //确认选择人员 生成计算机名
    async confirmSelectPerson() {
      if (!this.form.searchPersonResult.currentRow) {
        this.$message.warning("请选择人员！");
        return;
      }
      let row = this.form.searchPersonResult.currentRow;
      this.form.userName = row.samAccountName;
      this.form.fullDepartment = row.fullDepartment;
      this.form.searchPersonResult.show = false;
    },
    //搜索人员
    async searchPerson() {
      // this.$refs["addPersonalComputerForm"].validate(valid => {
      //   if (!valid) {
      //     return false;
      //   }
      // });

      if (!this.form.userName) return;
      this.form.searchPersonResult.loading = true;

      const queryParams = {
        ...this.form.searchPersonResult.page,
        displayName: this.form.userName,
      };
      const res = await personApi
        .searchPersonPage(queryParams)
        .catch()
        .finally((n) => (this.form.searchPersonResult.loading = false));
      if (res.success) {
        if (res.data.data.length > 1) {
          this.form.searchPersonResult.show = true;
          this.form.searchPersonResult.list = res.data.data;
          this.form.searchPersonResult.page.total =
            res.data.pagination.dataCount;
        } else if (res.data.data.length == 1) {
          this.form.searchPersonResult.currentRow = res.data.data[0];
          this.confirmSelectPerson();
        } else if (res.data.data == 0) {
          this.$message.warning("未找到符合条件的用户！");
          this.form.fullDepartment = "";
        }
      }
    },
  },
};
</script>
